import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN, APP_TIME } from '@/store/mutation-types'
import qs from 'qs'
import router from '@/router'
import { i18nRender } from '@/locales'

let showError401 = false
// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: '/api',
  timeout: 60000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = error => {
  console.log('#############', error)
  if (error.response) {
    const data = error.response.data
    if (error.response.status === 403) {
      notification.error({
        message: i18nRender('all.autotext352'),
        description: data.message
      })
    }
    // 导出blob失败专用
    if (error.response.status === 555) {
      const reader = new FileReader()
      reader.onload = () => {
        const json = JSON.parse(reader.result)
        notification.error({
          message: i18nRender('all.autotext133'),
          description: (json && json.detail) || i18nRender('all.autotext612')
        })
      }
      reader.readAsText(data)
    }
    if (error.response.status === 401 && !showError401) {
      showError401 = true
      notification.error({
        message: i18nRender('all.autotext1092'),
        description: i18nRender('all.autotext347')
      })
      store.dispatch('Logout').then(() => {
        setTimeout(() => {
          showError401 = false
          router.push({ name: 'login' })
        }, 1500)
      })
    }
    if (error.response.status === 404) {
      console.log(error, 'error')
      notification.error({
        message: i18nRender('all.autotext541'),
        description: i18nRender('all.autotext1382')
      })
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  config.headers.lang = storage.get('app_language', 'zh-CN')
  if (!config.headers['Content-Type']) {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    config.data = qs.stringify(config.data)
  }
  if (config.url !== '/boss/project/message/badge') {
    // 如果不是更新
    storage.set(APP_TIME, Date.now(), 30 * 1000)
  }

  const token = storage.get(ACCESS_TOKEN)

  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers.token = token
  }
  let proId = ''
  const pro = localStorage.getItem('CURRENT_PROID')
  if (pro) {
    proId = parseInt(pro)
  }
  config.headers.proId = proId
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use(response => {
  return new Promise(async (resolve, reject) => {
    let data = response.data
    // fixme: 迷惑行为？
    if (response.config.url === '/boss/log/export') {
      // 导出接口 特殊处理
      return resolve(data)
    } else if (response.config.url === '/boss/project/visit/export') {
      // 导出接口 特殊处理
      return resolve(data)
    } else if (response.config.url === '/boss/system/user/export') {
      // 导出接口 特殊处理
      return resolve(data)
    } else if (response.config.url === '/boss/project/manage/subjectExport') {
      // 导出接口 特殊处理
      return resolve(data)
    } else if (response.config.url === '/boss/budget/exportPDF') {
      // 导出接口 特殊处理
      return resolve(data)
    } else if (response.config.url === '/boss/project/manage/exportTemplate') {
      // 导出接口 特殊处理
      return resolve(data)
    } else if (response.config.url === '/boss/project/manage/exportContract') {
      // 导出接口 特殊处理
      return resolve(data)
    } else if (response.config.url === '/boss/project/apply/export') {
      // 导出接口 特殊处理
      return resolve(data)
    } else if (response.config.url === '/v2/boss/project/cost/export') {
      // 导出接口 特殊处理
      return resolve(data)
    } else if (response.config.url === '/boss/budget/export') {
      // 导出接口 特殊处理
      return resolve(data)
    } else if (response.config.url === '/boss/project/team/activityExport') {
      // 导出接口 特殊处理
      return resolve(data)
    } else if (
      response.config.url === '/boss/project/manage/person/downloadContract'
    ) {
      // 导出接口 特殊处理
      return resolve(data)
    } else if (response.config.url === '/boss/finance/record/download') {
      // 导出接口 特殊处理
      return resolve(data)
    }

    // 处理文件
    const { responseType = '' } = response.config
    if (responseType.toLowerCase() === 'blob') {
      if (data.type !== 'application/json') {
        return resolve(response)
      }
      // 如果返回的类型头是 json 说明后端异常，交给后面处理
      const responseJson = await new Response(data).json()
      if (responseJson) {
        // 拿到后端返回的真正的值
        data = responseJson
      }
    }
    if (data.status === '1') {
      return resolve(data.data)
    }
    const { disableInterceptorNotification } = response.config
    if (disableInterceptorNotification) return resolve(data)
    switch (data.status) {
      case '-10':
        const traceid = response.headers.traceparent
          ? response.headers.traceparent.split('-')[1]
          : ''
        const description = data.detail
        notification.error({
          message: i18nRender('all.autotext1235'),
          description: h => (
            <div>
              <div>{description}</div>
              {traceid && (
                <div style='width:100%;border-top: 1px solid #0F121B;padding: 10px 10px 10px 73px;position:absolute;left:0;bottom:0;'>
                  traceID: {traceid}
                </div>
              )}
            </div>
          ),
          style: {
            position: 'relative',
            paddingBottom: traceid ? '60px' : '16px'
          }
        })
        reject(data)
        break
      default: {
        notification.error({
          message: i18nRender('all.autotext1235'),
          description: data.detail
        })
        reject(data)
      }
    }
  })
}, errorHandler)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export { installer as VueAxios, request as axios }
